package com.bodacn.storagescan;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;

import java.math.BigDecimal;
import java.util.UUID;

public class ChangeActivity extends AppCompatActivity implements View.OnClickListener {
    private String TAG = this.getClass().getName();
    private final static int MSG_AllowScan=9000;
    private final static int MSG_ScanBarcodeOver=9001;
    private final static int MSG_FocusBarcode =9002;
    private final static int MSG_CallAgvResult =9003;
    public static final int MSG_ERROR = 9009;
    TextView txt_titleInv, tv_barcodeCaption,tv_ResultInfo;
    FrameLayout liner_title;
    Button btn_Query,btn_affirm;
    ImageButton btn_return;
    EditText edit_Barcode, edt_TrayCode,edt_PlaceNo;
    String curLoginUserNo,curLoginUser,curLoginTime;//操作员所属部门等信息;
    String FormType="",Caption="",PrBarcode="";
    int pageItemCount=8;
    boolean ScanSign=false;
    //拦截扫描枪输入部分
    String BarcodeStr="";
    ScannerManager scannerManager;
    private MainApplication mApp;
    JSONArray detailJSON;
    //全局变量
    Toast curToast;
    String TaskID= UUID.randomUUID().toString();
    /*
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (scannerManager.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change);
        InitView();
        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curLoginTime=paramBundle.getString("LoginTime");
        FormType=paramBundle.getString("FormType");
        Caption=paramBundle.getString("Caption");
        //初始提醒;
        curToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        //界面变量
        ((TextView)findViewById(R.id.tv_userName)).setText("用户:"+curLoginUser);
        //置标题颜色
        txt_titleInv.setText(Caption);
        txt_titleInv.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新界面;
                Message msg = new Message();
                msg.what = MSG_FocusBarcode;
                handler.removeMessages(msg.what);
                handler.sendMessage(msg);
            }
        },200);
        //拦截扫描事件
        /*
        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code,String deviceName) {
                Log.d(TAG, "code= " + code);
                playRingtone();
                edit_Barcode.setHint(code);
                ScanBarcode(code);
                edit_Barcode.setText("");
            }
        },this);

         */
        mApp=  (MainApplication) getApplication();
    }


    //插放音乐;
    private void playRingtone(){
        Uri notification = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }

    //判断是否为数字，不然不转
    public static boolean isNumer(String str) {
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    private void InitView(){
        btn_Query=findViewById(R.id.btn_Scan);
        btn_Query.setOnClickListener(this);
        tv_ResultInfo=findViewById(R.id.tv_ResultInfo);
        edt_TrayCode =findViewById(R.id.edt_TrayCode);
        edt_PlaceNo=findViewById(R.id.edt_PlaceNo);
        edit_Barcode=findViewById(R.id.edit_Barcode);
        edit_Barcode.setInputType(InputType.TYPE_NULL);
        edit_Barcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                edit_Barcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edit_Barcode, InputMethodManager.SHOW_FORCED);
            }
        });
        edit_Barcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event!=null){
                    //Log.e("Debug","-----------------------------Debug-----------------------------");
                    //System.out.println(event);
                    if ((event.getAction()== KeyEvent.ACTION_UP)&&(event.getKeyCode()== KeyEvent.KEYCODE_ENTER))
                    {
                        //虚拟键盘或实体键盘可考虑是否通过deviceID，或source来判断
                        // KeyEvent:KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_ENTER, scanCode=0, metaState=0, flags=0x16, repeatCount=0, eventTime=142515176, downTime=142515176, deviceId=-1, source=0x0 }
                        //隐藏键盘
                        //System.out.println(edit_Barcode.getText().toString());
                        String code=DBUtil.replaceBlank(edit_Barcode.getText().toString());
                        edit_Barcode.setHint(code);
                        ScanBarcode(code);
                        edit_Barcode.setText("");
                        return true;
                    }
                }
                return false;
            }
        });

        edit_Barcode.requestFocus();
        edit_Barcode.requestFocusFromTouch();
        liner_title=findViewById(R.id.liner_title);
        tv_barcodeCaption =findViewById(R.id.tv_barcodeCaption);
        txt_titleInv=findViewById(R.id.txt_titleInv);
        btn_return =findViewById(R.id.btn_return);
        btn_return.setOnClickListener(this);
        btn_affirm=findViewById(R.id.btn_affirm);
        btn_affirm.setOnClickListener(this);
        findViewById(R.id.btn_clear).setOnClickListener(this);

    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }


    @Override
    public void onClick(View view) {
        hideIM(view);
        switch (view.getId()){
            case R.id.btn_affirm:
                SubmitData(edt_TrayCode.getText().toString(), edt_PlaceNo.getText().toString(),"Bind");
                break;
            case R.id.btn_clear:
                SubmitData(edt_TrayCode.getText().toString(), edt_PlaceNo.getText().toString(),"Clear");
                break;
            case R.id.btn_return:
                finish();//关闭当前Activity，返回上一级;
                break;
            case R.id.btn_Scan:
                if ((edit_Barcode.getText()!=null)&&(edit_Barcode.getText().length()>0)) {
                    String code=edit_Barcode.getText().toString();
                    edit_Barcode.setHint(code);
                    ScanBarcode(code);
                    edit_Barcode.setText("");
                } else Toast.makeText(getApplicationContext(),"请先输入条码!", Toast.LENGTH_LONG).show();
                break;
            case R.id.btn_refreshDetail:

                hideIM(liner_title);
                break;
            default:
                break;
        }
    }


    private void SubmitData(String paramTrayCode, String paramPlaceNo, String paramOperType) {
        try {
            detailJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //组织WebService地址;
        if (TaskID.length()==0) TaskID=java.util.UUID.randomUUID().toString();
        String SqlComm = "Exec AGV_AgvChangeBarcode @TaskID='" + TaskID+"',@FormType='" + FormType + "',@TrayCode='" + paramTrayCode
                + "',@PlaceNo='" + paramPlaceNo+ "',@OperType='"+paramOperType+"',@UserNo='" + curLoginUserNo + "'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }




    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            hideIM(edit_Barcode);
            Bundle bundle=msg.getData();
            ScanSign=false;
            switch (msgId) {
                case MSG_CallAgvResult:
                    System.out.println(msg.obj);
                    System.out.println(msg.arg1);
                    tv_ResultInfo.setText(msg.obj.toString());
                    break;
                case MSG_FocusBarcode:
                    edit_Barcode.setEnabled(true);
                    edit_Barcode.selectAll();
                    edit_Barcode.requestFocus();
                    edit_Barcode.requestFocusFromTouch();
                    break;
                case MSG_ScanBarcodeOver:
                    fillScreen();
                    break;
                case MSG_AllowScan:
                    ScanSign=false;
                    break;
                case MSG_ERROR:
                    String HintInfo=bundle.getString("HintInfo");
                    curToast.setText(HintInfo);
                    curToast.show();
                    break;
                default:
                    break;
            }
        }
    };




    private void fillScreen() {
        if (detailJSON!=null&&detailJSON.length()>0){
            try {
                if (detailJSON.optJSONObject(0).has("TaskID")) TaskID=detailJSON.optJSONObject(0).getString("TaskID");
                if (detailJSON.optJSONObject(0).has("TrayCode")) edt_TrayCode.setText(detailJSON.optJSONObject(0).getString("TrayCode"));
                if (detailJSON.optJSONObject(0).has("PlaceNo")) edt_PlaceNo.setText(detailJSON.optJSONObject(0).getString("PlaceNo"));
                if (detailJSON.optJSONObject(0).has("ResultInfo")) tv_ResultInfo.setText(detailJSON.optJSONObject(0).getString("ResultInfo"));
                if (detailJSON.optJSONObject(0).has("FontColor")) tv_ResultInfo.setTextColor(GetColorValue(detailJSON.optJSONObject(0).getString("FontColor")));
                if (detailJSON.optJSONObject(0).has("ErrInfo") == true) {
                    // 创建对话框
                    AlertDialog alertDialog = new AlertDialog.Builder(this)
                            .setTitle("系统提示").setMessage(detailJSON.optJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).create();
                    alertDialog.show(); // 显示对话框
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if ((StrPenColor.indexOf("#")==0)&&(StrPenColor.length()==7)){
            int testColor= Integer.parseInt(StrPenColor.substring(1),16);
            int red = (testColor & 0xff0000) >> 16;
            int green = (testColor & 0x00ff00) >> 8;
            int blue = (testColor & 0x0000ff);
            PenColor= Color.rgb(red, green, blue);
        }else {
            if (isNumer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }


    //登陆校验;
    private void ScanBarcode(String paramBarcode){
        hideIM(edit_Barcode);
        try {
            detailJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //组织WebService地址;
        if (TaskID.length()==0) TaskID=java.util.UUID.randomUUID().toString();
        String SqlComm = "Exec AGV_AgvChangeBarcode @Barcode='" + paramBarcode + "',@TaskID='" + TaskID + "',@FormType='" + FormType + "',@TrayCode='" + edt_TrayCode.getText().toString()
                + "',@PlaceNo='" + edt_PlaceNo.getText().toString()+ "',@OperType='ScanBarcode',@UserNo='" + curLoginUserNo + "'";
        PrBarcode = paramBarcode;
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        ScanSign=true;
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    String OperType = "";
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        if (jsonArray.optJSONObject(0).has("OperType"))
                            OperType = jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE"))
                            OperType = jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (OperType.equals("ScanBarcode") == true
                                ||OperType.equals("Clear") == true
                                ||OperType.equals("Bind") == true) {
                            detailJSON = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_ScanBarcodeOver;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //刷新界面;
                            Message errmsg = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putString("HintInfo", jsonArray.optJSONObject(0).getString("SQLMessage"));
                            errmsg.what = MSG_ERROR;
                            errmsg.setData(bundle);
                            handler.removeMessages(errmsg.what);
                            handler.sendMessage(errmsg);
                        }
                    } else {
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle = new Bundle();
                        bundle.putString("HintInfo", "未返回任何数据!");
                        errmsg.what = MSG_ERROR;
                        errmsg.setData(bundle);
                        handler.removeMessages(errmsg.what);
                        handler.sendMessage(errmsg);
                    }
                } catch (Exception e) {
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putString("HintInfo", e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    handler.removeMessages(errmsg.what);
                    handler.sendMessage(errmsg);
                }
            }
        };
        new Thread(run).start();

    }




}
